package com.jnevision.clockin.service;

import java.time.LocalDate;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jnevision.clockin.mapper.ClockInMapper;
import com.jnevision.clockin.model.AttendanceRecordVO;
import com.jnevision.clockin.model.ClockIn;
import com.jnevision.common.CommonQuery;
import com.jnevision.personalattendance.mapper.PersonalAttendanceMapper;
import com.jnevision.personalattendance.model.PersonalAttendance;

/**
 * <p>
 * 工作打卡记录 服务实现类
 * </p>
 *
 * @author gavin
 * @since 2019-07-13
 */
@Service
public class ClockInServiceImpl extends ServiceImpl<ClockInMapper, ClockIn> {
    @Autowired
    private PersonalAttendanceMapper personalAttendanceMapper;

    public IPage<ClockIn> page(Page<ClockIn> page, String userId) {
        String start = LocalDate.now().withDayOfMonth(1).toString();
        String end = LocalDate.now().plusMonths(1).withDayOfMonth(1).toString();
        return this.baseMapper.page(page, userId, start, end);
    }

    public IPage<AttendanceRecordVO> attendanceRecord(Page<AttendanceRecordVO> page, CommonQuery query) {
        IPage<AttendanceRecordVO> records = this.baseMapper.attendanceRecord(page, query);
        records.getRecords().forEach(attendance -> {
            query.setUserId(attendance.getUserId());
            PersonalAttendance pa = this.personalAttendanceMapper.personal(query);

            int yingqin = 0, gongxiu = 0;
            if (null != pa) {
                for (int i = 0; i < pa.getDays().length; i++) {
                    if (StringUtils.equals(pa.getDays()[i], "√")) {
                        yingqin++;
                    } else if (StringUtils.equals(pa.getDays()[i], "休")) {
                        gongxiu++;
                    }
                }
            }

            Integer xiuxi = Optional
                .ofNullable(this.baseMapper.selectCount(new QueryWrapper<ClockIn>().eq("clock_in_status", 8)
                    .eq("user_id", query.getUserId()).ge("work_day", query.getStart()).lt("work_day", query.getEnd())))
                .orElse(0);

            attendance.setYingqin(String.valueOf(yingqin));
            attendance.setKetiao(String.valueOf(gongxiu - xiuxi));
        });
        return records;
    }

    public IPage<ClockIn> recordDetail(Page<ClockIn> page, CommonQuery query) {
        return this.baseMapper.recordDetail(page, query);
    }
}
